import axios, { type AxiosInstance } from 'axios';
// import { ElMessage } from 'element-plus';
// import { message } from 'antd';
import { getToken, setToken } from './';

interface RequestConfig {
  url: string;
  method: 'GET' | 'DELETE' | 'POST' | 'PUT';
  params?: any;
  data?: any;
}

// const [messageApi, contextHolder] = message.useMessage();

class HttpRequest {
  private instance: AxiosInstance;

  constructor() {
    this.instance = axios.create({
      baseURL: import.meta.env.VITE_API_BASE_URL,
      timeout: 30000
    });
    this.setRequestInterceptor();
    this.setResponseInterceptor();
  }

  // 请求拦截器
  private setRequestInterceptor() {
    this.instance.interceptors.request.use(config => {
      const token = getToken();
      if (token) config.headers.Authorization = token;
      return config;
    }, err => Promise.reject(err));
  }

  // 响应拦截器
  private setResponseInterceptor() {
    // { contextHolder }
    this.instance.interceptors.response.use(({ data }) => {
      if(Object.prototype.toString.call(data) === '[object Blob]') return data;
      // 公共报错和data属性解构
      if (data.code !== 10000) {
        // messageApi.error(data.msg);
        console.log(new Error(data.msg));
      }
      if (data.code === 10200) {
        setToken('');
        location.reload();
      }
      return data;
    }, err => {
      // messageApi.error(err.message || '请求出错');
      console.log(new Error(err.message || '请求出错'));
      return Promise.reject(err);
    });
  }

  private request<T>(config: RequestConfig): Promise<T> {
    return this.instance.request(config);
  }

  get<T = any>(url: string, params = {}, config = {}) {
    return this.request<T>({
      url,
      method: 'GET',
      params,
      ...config
    });
  }

  delete<T = any>(url: string, params = {}, config = {}) {
    return this.request<T>({
      url,
      method: 'DELETE',
      params,
      ...config
    });
  }

  post<T = any>(url: string, data = {}, config = {}) {
    return this.request<T>({
      url,
      method: 'POST',
      data,
      ...config
    });
  }

  put<T = any>(url: string, data = {}, config = {}) {
    return this.request<T>({
      url,
      method: 'PUT',
      data,
      ...config
    });
  }
}

export default new HttpRequest();
